<?php
/**
 * Created by PhpStorm.
 * User: hjlan
 * Date: 2016/2/2
 * Time: 15:24
 * 优惠券后台
 */

namespace App\Services\Coupons;


use App\Services\Tool\ImageProcessor\ImagickTool;
use Illuminate\Http\Request;
use Request as Request1;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use App\Services\Tool\Coupons\CouponsTool;
use App\Services\Tool\GeneralTool;
use App\Services\Tool\Jpush\JpushTool;
use App\Services\Tool\DataBase\SQL;

class CouponsServices
{
    protected $imagickTool;
    protected $zip;

    /**
     * CouponsServices constructor.
     */
    public function __construct(ImagickTool $imagickTool,
                                Zip $zip,
                                CouponsTool $couponsTool)
    {
        $this->imagickTool = $imagickTool;
        $this->zip         = $zip;
        $this->couponTool  = $couponsTool;

    }

    /**
        主内容
     */

    /**
     * 优惠券生成
     * @param int $no_of_codes//定义生成优惠码个个数
     * @param array $exclude_codes_array//老优惠券组
     * @param int $code_length//优惠码的长度
     * @return array //返回数组
     */
    function generate_promotion_code($no_of_codes,$exclude_codes_array='',$code_length = 4)
    {
        $characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        $promotion_codes = array();
        for($j = 0 ; $j < $no_of_codes; $j++)
        {
            $code = "";
            for ($i = 0; $i < $code_length; $i++)
            {
                $code .= $characters[mt_rand(0, strlen($characters)-1)];
            }

            if(!in_array($code,$promotion_codes))
            {
                if(is_array($exclude_codes_array))
                {
                    if(!in_array($code,$exclude_codes_array))
                    {
                        $promotion_codes[$j] = $code;
                    }
                    else
                    {
                        $j--;
                    }
                }
                else
                {
                    $promotion_codes[$j] = $code;
                }
            }
            else
            {
                $j--;
            }
        }
        return $promotion_codes;
    }

    /**
     * 生成优惠券
     * @param $request
     * @return array
     */
    public  function addcoupons($coupon){
        try{
        //添加优惠券
        DB::beginTransaction();
        $identifiers=$this->generate_promotion_code($coupon['num'],'',8);
        for($i=0;$i<$coupon['num'];$i++){
            $coupon_id=$coupon['channel_id'].$identifiers[$i];
            //插入追加优惠券
            DB::table('coupons')->insert(array(
                'channel_id' => $coupon['channel_id'],
                'coupon_id'  => $coupon_id,
                'price'      => $coupon['price'],
                'type'       => $coupon['binding_type'],
                'begin_time' => $coupon['begin_time'],
                'end_time'   => $coupon['end_time'],
                'created_at' => time(),
                'updated_at' => time()));
        }
        $coupon['state']=1;
        $coupon['created_at']=time();
        $coupon['updated_at']=time();
        $ins_res=DB::table('channels')->insert($coupon);
        return $ins_res;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return 0;
        }finally{
            DB::commit();
        }
    }
    /**
        添加使用范围
        参数:
            优惠券
            channel_id          渠道编号
            type                类型 类型 0满额度 1产品模版 2商品 3品牌
            quota               满减额度
            reg_id              资源id
            现金券
            channel_id          渠道编号
     */
    function addChannelMap($input, $coupon_type = 1){
        if(!isset($input['channel_id'])) return GeneralTool::createResult('','M00002');
        $coupon_type_channel = $this->couponTool->get_coupon_type_by_channel_id($input);
        if($coupon_type == 1 && (isset($coupon_type_channel) || $coupon_type_channel != 1)) return GeneralTool::createResult('','M05044');
        if($coupon_type == 2){
            $map = $this->couponTool->get_channel_maps_count(['channel_id' => $input['channel_id'],
                                                              'type'       => 0,
                                                              'state'      => 1]);
            $result = $map ? 1 : $this->couponTool->insert_channel_maps(['channel_id' => $input['channel_id'],
                                                                         'type'       => 0,
                                                                         'state'      => 1]);
            return $result ;
        }else if($coupon_type == 1){
            if(!isset($input['type']) ||
                !isset($input['quota']) ||
                !isset($input['reg_id']) ||
                !is_numeric($input['quota']) ||
                $input['quota'] < 0)
                return GeneralTool::createResult('','M00002');

            $can = $this->couponTool->resource_can_use($input);
            if($can != 'M00000') return GeneralTool::createResult('',$can);

            $map = $this->couponTool->get_channel_maps_count(['channel_id' => $input['channel_id'],
                                                              'type'       => $input['type'],
                                                              'reg_id'     => $input['reg_id'],
                                                              'state'      => 1]);
            $result = $this->couponTool->update_channel_maps(['where'  => ['channel_id' => $input['channel_id'],
                                                                           'type'       => $input['type'],
                                                                           'reg_id'     => $input['reg_id'],
                                                                           'state'      => 1],
                                                              'update' => ['quota'      => $input['quota'],
                                                                           'updated_at' => time()]]);
            return GeneralTool::createResult('','M00000');
        }
    }
    /**
     * 更新优惠券
     * @param $coupon
     * @return mixed
     */
    public  function updatecoupons($coupon){
        try{
        $coupon['state']=1;
        $coupon['updated_at']=time();
        DB::beginTransaction();
        $update_res=DB::table('channels')->where(array('id'=>$coupon['id'],'state'=>1))
                                         ->update($coupon);
        $channel=DB::table('channels')->where(array('id'=>$coupon['id'],'state'=>1))
                                       ->first();
        if(isset($coupon['begin_time'])&&isset($coupon['begin_time'])&&!empty($channel)){
            DB::table('coupons')->where(array('channel_id'=>$channel->channel_id,'state'=>1))
                                ->update(array(
                                         'begin_time'=>$channel->begin_time,
                                         'price'=>$channel->price,
                                         'end_time'=>$channel->end_time,
                                         'updated_at'=>time()));
        }
        return $update_res;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return 0;
        }finally{
            DB::commit();
        }
    }
    /**
     * 优惠券列表
     * @param $request
     * @return array
     */
    public  function  couponslist($request){
        $channels=DB::table('channels')->where(array('state'=>1))
                                       ->orderBy('created_at', 'DESC')
                                       ->paginate(8);
        foreach ($channels as $channel){
            $channel->coupons_used=$this->getCouponsUsedByChannelId($channel->channel_id);
            $channel->coupons_receive=$this->getCouponsReceiveByChannelId($channel->channel_id);
            $channel->use = DB::table('coupons')
                            ->where(['channel_id' => $channel->channel_id,
                                     'state' => 1])
                            ->where('using_time','>',0)
                            ->count();
            $channel->send = DB::table('coupons')
                             ->where(['channel_id' => $channel->channel_id,
                                     'state' => 1])
                             ->where('user_id','<>','')
                             ->count();
        }
       return $channels;
    }

    /***
     * 优惠券绑定优惠券列表
     * @param $request
     * @return mixed
     */
    public  function  getCouponBindingCouponlist($request){
        $coupons=DB::table('couponbindingcoupons')->where(array('state'=>1))
            ->orderBy('created_at', 'DESC')
            ->paginate(8);
        return $coupons;
    }

    /***
     * 礼包优惠券渠道绑定普通优惠券渠道
     * @param $channel_id
     * @return mixed
     */
    public  function  getChannelidbindingByChIds($channel_id){
        $bindingchids=DB::table('channelidbindingchids')->where(array('state'=>1,'channel_id'=>$channel_id))
            ->orderBy('updated_at', 'DESC')
            ->get();
        foreach ($bindingchids as $bindingchid){
            $channel=self::getChannelByChannelId($bindingchid->b_channel_id);
            if(empty($channel)){
                $bindingchid->channel_name='';
                $bindingchid->channel_desc='';
            }
            $bindingchid->channel_name=$channel->name;
            $bindingchid->channel_desc=$channel->desc;
        }
        return $bindingchids;
    }

    /***
     * 优惠券获取对应渠道
     * @param $coupon_id
     * @return mixed
     */
    public  function  getChannelIdByCouponId($coupon_id){
        $channel_id=DB::table('coupons')->where(array('state'=>1,'coupon_id'=>$coupon_id))
                                         ->value('channel_id');
        return $channel_id;
    }

    /***
     * 查看某一渠道下可使用，未被领取优惠券数量
     * @param $channel_id
     * @return mixed
     */
    public function getCanUseCouponNumByChannelId($channel_id)
    {
        $num=DB::table('coupons')->where(array('state'=>1,'channel_id'=>$channel_id,'user_id'=>''))
                                  ->where('end_time','>',time()+30*60)
                                  ->count();
        return $num;
    }
    /***
     * 优惠券已使用
     * @param $channel_id
     * @return int
     */
    public  function  getCouponsUsedByChannelId($channel_id){
        if(empty($channel_id)){
            return 0;
        }
        $num=DB::table('coupons')->where(array('state'=>1,'channel_id'=>$channel_id))
                                   ->whereNotIn('using_time',array(0))
                                   ->count();
        return $num;
    }

    /***
     * 优惠券未领取
     * @param $channel_id
     * @return int
     */
    public  function  getCouponsReceiveByChannelId($channel_id){
        if(empty($channel_id)){
            return 0;
        }
        $num=DB::table('coupons')->where(array('state'=>1,'channel_id'=>$channel_id))
                                   ->where('user_id','')
                                   ->count();
        return $num;
    }

    /***
     * 渠道Id获取优惠券
     * @param $channel_id
     * @return null]
     */
    public  function  getCouponById($id){
        if(!isset($id)){
            return null;
        }
        $coupon=DB::table('coupons')->where(array('state'=>1,'id'=>$id))
                                     ->first();
        return $coupon;
    }
    /**
     * 检查渠道id是不是使用过
     * @param $request
     * @return array
     */
    public  function checkchannelid($request){
        $channel_id=$request->get("channel_id");
        $checked_state=$request->get("checked_state");
        if(empty($channel_id)){
            return array("message"=>"无渠道号","state"=>"M00001");
        }
        $channels=DB::table('channels')->where(array('channel_id'=>$channel_id,'state'=>1))->count();
        if($channels!=0){
            if(isset($checked_state)&&$checked_state==1){
                return array("message"=>"可追加","state"=>"M00000");
            }else{
                return array("message"=>"已使用","state"=>"M00001");
            }
        }else{
            return array("message"=>"可使用","state"=>"M00000");
        }
    }

    /**
     * 优惠劵发放页面
     * @param $request
     * @return array|\Illuminate\Http\RedirectResponse
     */
    public function  issuing($id){
        $channel=DB::table('channels')->where(array('id'=>$id,'state'=>1))->first();
        return $channel;
    }

    /**
     * 生成优惠券excel
     * @param $request
     * @return array|\Illuminate\Http\RedirectResponse
     */
   public function generatexls($channel_id){
       try{
       $channel=DB::table('channels')->where(array('channel_id'=>$channel_id,'state'=>1))->first();
       if(!empty($channel)&&($channel->binding_type==2)){
           $coupon_id1s=DB::table('coupons')->where(array('channel_id'=>$channel_id,'state'=>1))
                                ->pluck('coupon_id');
           $coupon_id2s=DB::table('coupons')->where(array('state'=>1))
                                ->whereIn('coupon_id',$coupon_id1s)
                                ->pluck('coupon_id');
           //礼包优惠券
           $coupons=DB::table('coupons')->where(array('state'=>1,'using_time'=>0,'is_bind'=>1,"issued_coupon"=>1))
               ->whereIn('coupon_id',$coupon_id2s)
               ->where('user_id','')
               ->select("channel_id","coupon_id","price","begin_time","end_time")
               ->get();
       }else{
           $coupons=DB::table('coupons')->where(array('channel_id'=>$channel_id,'state'=>1,'using_time'=>0,'is_bind'=>0,"issued_coupon"=>1))
               ->where('user_id','')
               ->select("channel_id","coupon_id","price","begin_time","end_time")->get();
       }
       $rows=array();
       if(empty($coupons)){
           return redirect()->back()->with('error_message','没有符合条件的优惠劵！');
       }
       foreach($coupons as $coupon){
           $arr=array("渠道编号"=>$coupon->channel_id,"编号"=>$coupon->coupon_id,"额度"=>$coupon->price,"开始时间"=>date("Y-m-d H:i:s",$channel->begin_time),"结束时间"=>date("Y-m-d H:i:s",$coupon->end_time));
           $rows[]=$arr;
       }
       $time=time();
       Excel::create($time, function($excel) use ($rows) {
           $excel->sheet('coupon', function($sheet) use ($rows) {
               $sheet->fromArray($rows);
           });
       })->store('xls', public_path('excel'));
       $get_xls_url=asset('excel/'.$time.".xls");
       return array("message"=>"成功生成excel！！","state"=>"M00000","url"=>$get_xls_url);
       }catch (\Exception $e) {
           Log::info($e);
           return array("message" => "成功生成excel出错！！", "state" => "M00001", "url" => "");
       }
   }

    /**
     * 创建文件夹
     * @param $path
     */
    function mkFolder($path)
    {
        try{
        if(!is_readable($path))
        {
            is_file($path) or mkdir($path,0700);
        }
        return true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 渠道详情
     * @param $request
     * @return array
     */
    function detail($request){
        $channel_id=$request->get("channel_id");
        if(empty($channel_id)){
            return array("message"=>"无渠道号","state"=>"M00001");
        }
        $channel=DB::table('channels')->where(array('channel_id'=>$channel_id,'state'=>1))
                                      ->first();
        if(empty($channel)){
            return array("message"=>"符合条件的渠道编号不存在！","state"=>"M00001");
        }
        return $channel;
    }

    /**
     * 删除优惠券
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete($id){
        $info = DB::table('channels')
                ->where(['channel_id' => $id, 'state' => 1])
                ->first();
        if(!isset($info)) return ['state' => 2, 'message' => '优惠券不存在'];
        //判断优惠券是否已发放
        $count = DB::table('coupons')
                 ->where(['channel_id' => $id, 'state' => 1])
                 ->where('user_id', '<>', '')
                 ->count();
        if($count) return ['state' => 2, 'message' => '优惠券已发放，无法删除'];
        $bind = SQL::count(['table' => 'channelidbindingchids',
                            'where' => ['b_channel_id' => $id, 'state' => 1]]);
        if($bind) return ['state' => 2, 'message' => '该优惠券已与其他优惠券绑定，请先解绑'];
        if($info->binding_type == 2) CouponsTool::delete_banding($id);
        CouponsTool::delete_channel_coupons($id);
        return ['state' => 1, 'message' => '删除成功'];
    }

    /**
     * 获取channel
     * @param $id
     * @return mixed
     */
    public function getChannelById($id){
        return DB::table('channels')->where(array('id'=>$id))->first();
    }

    /**
     * 获取 channel
     * @param $channel_id
     * @return mixed
     */
    public function getChannelByChannelId($channel_id){
        if(empty($channel_id)){
            return null;
        }
        return DB::table('channels')->where(array('channel_id'=>$channel_id))->first();
    }
    /**
     * 优惠券导入到数据库中
     * @param $excel_path  excel存放路径
     * @return bool 执行成功
     */
    public function excel2DB($excel_path)
    {
        try{
            if(!file_exists($excel_path)){
                return false;
            }
            Excel::load($excel_path, function($reader) use( &$res ) {
                $reader = $reader->getSheet(0);
                $res = $reader->toArray();
            });
            foreach ($res as $re){
                DB::table('coupons')->insert(array(
                ));
            }
        }catch (\Exception $e){
            Log::info('exist导入数据库出错');
            Log::info($e);
            return false;
        }
    }

    /***
     * 搜索品牌
     * @param $search 搜索内容
     * @return mixed
     */
    public function SearchBrands($search)
    {
        $brands = DB::table('brands')->where('brand_name','like','%'.$search.'%')
                                     ->where('state',1)
                                     ->orderBy('sort','desc')
                                     ->select('id as brand_id','brand_name')
                                     ->get();
        return $brands;
    }
    /***
     * 搜索作品
     * @param $search
     * @return mixed
     */
    public function SearchCreates($search)
    {
        $creates = DB::table('creates')->where('title_search','like','%'.$search.'%')
                                        ->where(array('state'=>1,'is_public'=>1))
                                        ->select('create_id','title')
                                        ->get();
        foreach ($creates as $create){
            $create->title=empty($create->title)?'':pack('H*',$create->title);
        }
        return $creates;
    }

    /***
     * 渠道搜索
     * @param $search
     * @param int $binding_type  1 绑定优惠资源 2绑定 优惠券
     * @return mixed
     */
    public function SearchCoupons($search,$binding_type=1,$channel_id='')
    {
        $ids=DB::table('channels')->where('name','like','%'.$search.'%')
            ->orWhere('channel_id','like','%'.$search.'%')
            ->pluck('id');
        if(empty($channel_id)){
            $channels=DB::table('channels')->where('end_time','>',time())
                ->where(array('state'=>1,'binding_type'=>$binding_type))
                ->whereIn('id',$ids)
                ->get();
        }else{
         $channels=DB::table('channels')->where('end_time','>',time())
                ->where('channel_id','<>',$channel_id)
                ->where(array('state'=>1,'binding_type'=>$binding_type))
                ->whereIn('id',$ids)
                ->orderBy('updated_at','DESC')
                ->get();
        }
        return $channels;
    }

    /***
     * 根据channel_id，当前时间能不能绑定礼包优惠券
     * @param $channel_id
     * @return bool
     */
    public function canBindingChannelByChannelId($channel_id)
    {
        if(empty($channel_id)){
            return false;
        }
        $num=DB::table('channels')->where('end_time','>',time())
            ->where(array('state'=>1,'binding_type'=>1,'channel_id'=>$channel_id))
            ->count();
        return ($num==0)?false:true;
    }
    public function bindingCoupons(array $ch_ids,$channel_id){
        try{
        DB::beginTransaction();
        $un_able_use_channels=array();
        foreach ($ch_ids as $ch_id){
         $channel_exist=self::channelExistByIdAndState($ch_id,1);
            if(!$channel_exist){
                $un_able_use_channels[]=$ch_id;
            }else{
                DB::table('channelidbindingchids')->insert(
                    array(
                    'channel_id'=>$channel_id,
                    'b_channel_id'=>$ch_id,
                    'created_at'=>time(),
                    'updated_at'=>time(),
                ));
            }
        }
        return empty($un_able_use_channels)?true:$un_able_use_channels;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /**
     * @return ImagickTool
     */
    public function deleteChannelidbindingchidsByChannelId($channel_id)
    {
        if(empty($channel_id)){
            return false;
        }
        DB::table('channelidbindingchids')->where(array(
            'channel_id'=>$channel_id,
            'state'=>1
        ))->update(array(
            'state'=>0,
            'updated_at'=>time(),
        ));
        return true;
    }
    /***
     * 判断渠道是不是存在
     * @param $channel_id
     * @param int $state
     * @return bool
     */
    public function channelExistByIdAndState($id,$state=1){
        if(empty($id)){
            return false;
        }
        $num=DB::table('channels')->where(array(
            'id'=>$id,
            'state'=>$state,
        ))->count();
        return empty($num==0)?false:true;
    }
    /***
     * 搜索产品
     * @param $search
     * @return mixed
     */
    public function SearchProducts($search)
    {
        $products = DB::table('products')->where('name','like','%'.$search.'%')
                                         ->where('state',1)
                                         ->select('product_id','name','brand_id')
                                         ->get();
        foreach ($products as $product){
            $brand_name=DB::table('brands')->where(array('id'=>$product->brand_id))->value('brand_name');
            $brand_name=empty($brand_name)?'':$brand_name;
            $product->name=$brand_name.' > '.$product->name;
        }
        return $products;
    }
    /**
     * 数据验证
     * @param Request $request
     * @param $check_data
     * @return mixed
     */
    public function store(Request $request,$check_data)
    {
        $v = Validator::make($request->all(), $check_data);
        return $v;
    }
    /**
     * 活动名获取渠道
     * @param $name
     * @return object
     */
    public function getChannelsByName($name){
        if(empty($name)){
            return (object)array();
        }
        return DB::table('channels')->where(array('state'=>1,'name'=>$name))->first();
    }
    /***
     * 添加优惠券使用范围
     * @param array $data
     * @return bool
     */
    public function addUseRange(array $data)
    {
        try{
            $product_ids = $data['product_ids'];
            $create_ids  = $data['create_ids'];
            $brand_ids   = $data['brand_ids'];
            $id          = $data['id'];
            $range_type  = $data['range_type'];
            $channel     = $this->getChannelById($id);
            $time        = time();
            if(empty($channel)){
                return false;
            }
            DB::beginTransaction();
            // 全部商品优惠
            if($range_type==0){
                DB::table('channel_maps')->insert(array(
                                           'channel_id' => $channel->channel_id,
                                           'reg_id'     => '',
                                           'type'       => 0,
                                           'state'      => 1,
                                           'quota'      => $data['quota'],
                                           'created_at' => $time,
                                           'updated_at' => $time
                                         ));
            }else{
                if(!empty($product_ids)){
                    foreach ($product_ids as $product_id){
                        DB::table('channel_maps')->insert(array(
                            'channel_id' => $channel->channel_id,
                            'reg_id'     => $product_id,
                            'type'       => 1,
                            'state'      => 1,
                            'created_at' => $time,
                            'updated_at' => $time
                        ));
                    }
                }
                if(!empty($create_ids)){
                    foreach ($create_ids as $create_id){
                        DB::table('channel_maps')->insert(array(
                            'channel_id' => $channel->channel_id,
                            'reg_id'     => $create_id,
                            'type'       => 2,
                            'state'      => 1,
                            'created_at' => $time,
                            'updated_at' => $time
                        ));
                    }
                }
                if(!empty($brand_ids)){
                    foreach ($brand_ids as $brand_id){
                        DB::table('channel_maps')->insert(array(
                            'channel_id' => $channel->channel_id,
                            'reg_id'     => $brand_id,
                            'type'       => 3,
                            'state'      => 1,
                            'created_at' => $time,
                            'updated_at' => $time
                        ));
                    }
                }
            }
            return true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 根据渠道编号获取，对应优惠券优惠范围
     * @param $channel_id
     * @return mixed
     */
    public function getChannelMapsByChannelId($channel_id)
    {
        $input = Request1::all();
        if(empty($channel_id)){
            $channel_id='0';
        }
        $channel_maps=DB::table('channel_maps')->where(array(
                                  'channel_id'=>$channel_id,
                                  'state'=>1
                                 ))
                               ->orderBy('created_at', 'DESC')
                               ->paginate(8);
        foreach ($channel_maps as $channel_map){
            if($channel_map->type==1){
                $res_name=$this->couponTool->getProductTempNameByProductTempId($channel_map->reg_id);
            }elseif ($channel_map->type==2){
                $res_name=$channel_map->reg_id;
            }elseif($channel_map->type==3){
                $res_name=$this->couponTool->getBrandNameById($channel_map->reg_id);
            }
            $res_name=(!isset($res_name)||empty($res_name))?'':$res_name;
            $channel_map->res_name=$res_name;
        }
        $channel_maps->appends($input)->render();
        return $channel_maps;
    }

    /****
     * 渠道id获取该渠道对应所有优惠范围
     * @param $channel_id
     * @return mixed
     */
    public function getChannelAllMapsByChannelId($channel_id)
    {

        if(empty($channel_id)){
            $channel_id='0';
        }
        $channel_maps=DB::table('channel_maps')->where(array(
                                             'channel_id'=>$channel_id,
                                             'state'=>1
                                              ))
                                              ->orderBy('type', 'DESC')
                                              ->get();
        foreach ($channel_maps as $channel_map){
            if($channel_map->type==1){
                $res_name=$this->couponTool->getProductTempNameByProductTempId($channel_map->reg_id);
            }elseif ($channel_map->type==2){
                $res_name=$channel_map->reg_id;
            }elseif($channel_map->type==3){
                $res_name=$this->couponTool->getBrandNameById($channel_map->reg_id);
            }
            $res_name=(!isset($res_name)||empty($res_name))?'':$res_name;
            $channel_map->res_name=$res_name;
        }
        return $channel_maps;
    }
    /**
     * 作品id获取作品名
     * @param $create_id
     * @return string
     */
    public function getCreateNameById($create_id){
        if(empty($create_id)){
            return '';
        }
        $title_search=DB::table('creates')->where(array('create_id'=>$create_id))->value('title_search');
        return empty($title_search)?"":$title_search;
    }

    /**
     * 产品id获取产品名
     * @param $product_id
     * @return string
     */
    public function getProductNameById($product_id){
        if(empty($product_id)){
            return '';
        }
        $product=DB::table('products')->where(array('product_id'=>$product_id))
                                      ->select('name','brand_id')->first();
        $name='';
        if(!empty($product)){
            $brand_name=$this->getBrandNameById($product->brand_id);
            $brand_name=empty($brand_name)?'':$brand_name;
            $name.=$brand_name.' > '.$product->name;
        }
        return $name;
    }

    /**
     * 品牌id获取品牌名
     * @param $brand_id
     * @return string
     */
    public function getBrandNameById($brand_id){
        if(empty($brand_id)){
            return '';
        }
        return DB::table('brands')->where(array('id'=>$brand_id))->value('brand_name');
    }
    /**
     * 优惠资源删除
     * @param $id
     * @return bool
     */
    public function channelResDelete($id)
    {
        if(empty($id)){
            return false;
        }
        $res=DB::table('channel_maps')->where(array(
                                     'id'=>$id
                                     ))->update(array(
                                         'updated_at'=>time(),
                                         'state'=>0
                                     ));
        return ($res==1)?true:false;
    }
    public function channelResUpdateQuota($id,$quota)
    {
        if(empty($id)){
            return false;
        }
        $res=DB::table('channel_maps')->where(array(
            'id'=>$id
        ))->update(array(
            'updated_at'=>time(),
            'quota'=>$quota
        ));
        return ($res==1)?true:false;
    }
    /***
     * 渠道使用范围更新
     * @param $data
     * @return bool
     *
     */
    public function channelUseRangeUpdate($data){
        try{
            $channel=DB::table('channels')->where(array('id'=>$data['id']))->first();
            if(empty($channel)){
                return false;
            }
            DB::table('channel_maps')->where(array(
                                      'channel_id'=>$channel->channel_id
                                      ))->delete();
            $product_ids=$data['product_ids'];
            $create_ids=$data['create_ids'];
            $brand_ids=$data['brand_ids'];
            $id=$data['id'];
            $range_type=$data['range_type'];
            $channel=$this->getChannelById($id);
            if(empty($channel)){
                return false;
            }
            $time=time();
            DB::beginTransaction();
            // 全部商品优惠
            if($range_type==0){
                DB::table('channel_maps')->insert(array(
                                         'channel_id'=>$channel->channel_id,
                                         'reg_id'=>'',
                                         'type'=>0,
                                         'state'=>1,
                                         'quota'=>$data['quota'] ,
                                         'created_at'=>$time,
                                         'updated_at'=>$time,
                                           ));
            }else{
                if(!empty($product_ids)){
                    foreach ($product_ids as $product_id){
                        DB::table('channel_maps')->insert(array(
                            'channel_id'=>$channel->channel_id,
                            'reg_id'=>$product_id,
                            'type'=>1,
                            'state'=>1,
                            'created_at'=>$time,
                            'updated_at'=>$time,
                        ));
                    }
                }
                if(!empty($create_ids)){
                    foreach ($create_ids as $create_id){
                        DB::table('channel_maps')->insert(array(
                            'channel_id'=>$channel->channel_id,
                            'reg_id'=>$create_id,
                            'type'=>2,
                            'state'=>1,
                            'created_at'=>$time,
                            'updated_at'=>$time,
                        ));
                    }
                }
                if(!empty($brand_ids)){
                    foreach ($brand_ids as $brand_id){
                        DB::table('channel_maps')->insert(array(
                            'channel_id'=>$channel->channel_id,
                            'reg_id'=>$brand_id,
                            'type'=>3,
                            'state'=>1,
                            'created_at'=>$time,
                            'updated_at'=>$time,
                        ));
                    }
                }
            }
            return true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /****
     * 更新库存
     * @param $id
     * @param $num
     * @return bool
     */
    public function updateStock($id,$num)
    {
        if(empty($id)){
            return false;
        }
        $res= DB::table('favorable_gifts')->where(array('id' => $id, 'state' => 1))
            ->update(array(
                'num'=>$num,
                'updated_at'=>time()
            ));
        return ($res==1)?true:false;
    }

    /***
     * 礼包券绑定单券
     * @param array $sel_channels
     * @param $channel_id
     * @return bool
     */
    public function bindingChIdsStep2(array $sel_channels,$channel_id){
        try{
            DB::beginTransaction();
            $time=time();
            $channel=self::getChannelByChannelId($channel_id);
            if(empty($channel)||($channel->state!=1)){
                throw new \Exception("礼包优惠券不存在");
            }
            //礼包券解绑
            self::removeBindCouponIdsByChannelId($channel_id);
            for ($i=1;$i<=$channel->num;$i++){
                //礼包
                $coupon_id_arr=self::getCanBindingCouponIdsByChannelIdAndNum($channel_id,1,2);
                if(empty($coupon_id_arr)){
                    throw new \Exception("无法获取礼包券");
                }
                foreach ($sel_channels as $sel_channel){
                    $num=$sel_channel->num;
                      Log::info('数量：'.$num);
                    $has_num=self::getCanBindCouponIdNumByChannelId($sel_channel->channel_id);
                    if($has_num<$num){
                        throw new \Exception("可用优惠券数量不足");
                    }
                    //更新礼包优惠券绑定单券数量
                    self::updateChannelidbindingchidsByChannelIdAndBChannelId($channel_id,$sel_channel->channel_id,$num);
                      // //单券可绑定优惠券
                    $binding_coupon_ids=self::getCanBindingCouponIdsByChannelIdAndNum($sel_channel->channel_id,$num,1);
                      //礼包优惠券
                    foreach ($binding_coupon_ids as $binding_coupon_id){
                        $time=time();
                        DB::table('couponbindingcoupons')->insert(array(
                          'coupon_id'=>$coupon_id_arr[0],
                          'b_coupon_id'=>$binding_coupon_id,
                          'state'=>1,
                          'created_at'=>$time,
                          'updated_at'=>$time,
                        ));
                        /*
                        DB::table('coupons')->where(array('coupon_id'=>$binding_coupon_id))->update(array(
                            'is_bind'=>1,
                            'state'=>1,
                            'updated_at'=>$time,
                        ));
                        */
                    }

                }
            }
            return true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 礼包券解绑
     * @param $channel_id
     * @return bool
     */
    public function removeBindCouponIdsByChannelId($channel_id)
    {
        try{
            DB::beginTransaction();
        $coupon_ids=DB::table('coupons')->where(array('channel_id'=>$channel_id,'state'=>1))
                                         ->pluvk('coupon_id');
        $b_coupon_ids=DB::table('couponbindingcoupons')->where(array('state'=>1))
            ->whereIn('coupon_id',$coupon_ids)
            ->pluck('b_coupon_id');
        DB::table('coupons')->where(array('state'=>1))
            ->whereIn('coupon_id',$b_coupon_ids)
            ->update(array(
                'is_bind'=>0,
                'updated_at'=>time()
            ));
        DB::table('couponbindingcoupons')->where(array('state'=>1))
            ->whereIn('coupon_id',$coupon_ids)
            ->delete();
            return true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }
    /***
     * 取指定条数单券或者礼包券
     * @param $channel_id
     * @param int $num
     * @param int $type 1 单券 2 礼包券
     * @return array
     */
    public function getCanBindingCouponIdsByChannelIdAndNum($channel_id,$num=1,$type=1)
    {
        if(empty($channel_id)){
            return array();
        }
        if($type==1){
            //单券
            $coupon_ids=DB::table('coupons')->where('user_id','')
                ->where(array('state'=>1,'type'=>1,'is_bind'=>0,'channel_id'=>$channel_id))
                ->take($num)
                ->pluck('coupon_id');
        }else{
            //礼包券
            $coupon_ids=DB::table('coupons')
                ->where(array('state'=>1,'type'=>2,'is_bind'=>0,'channel_id'=>$channel_id))
                ->take($num)
                ->pluck('coupon_id');
        }
        return $coupon_ids;
    }

    /***
     * 礼包优惠券绑定优惠券
     * @param $coupon_id
     * @return null
     */
    public function getCouponbindingcouponsByCouponId($coupon_id)
    {
        if(empty($coupon_id)){
            return null;
        }
        $coupon=DB::table('couponbindingcoupons')->where(array('state'=>1,'coupon_id'=>$coupon_id))->first();
        return $coupon;
    }
    /***
     * 查某一渠道下可用于绑定的单券
     * @param $channel_id
     * @return int
     */
    public function getCanBindCouponIdNumByChannelId($channel_id)
    {
        if(empty($channel_id)){
            return 0;
        }
        $num=DB::table('coupons')->where('user_id','')
            ->where(array('state'=>1,'is_bind'=>0,'channel_id'=>$channel_id))
            ->count();
        return $num;
    }
    /***
     * 礼包券渠道和绑定优惠券渠道
     * @param $channel_id
     * @param $b_channel_id
     * @return null
     */
    public function getChannelidbindingchidsByChannelIdAndBChannelId($channel_id,$b_channel_id)
    {
        if(empty($channel_id)||empty($b_channel_id)){
            return null;
        }
        $channelidbindingchid=DB::table('channelidbindingchids')
            ->where(array('state'=>1,'b_channel_id'=>$b_channel_id,'channel_id'=>$channel_id))
            ->first();
        return $channelidbindingchid;
    }

    /***
     *  更新礼包优惠券绑定单券数量
     * @param $channel_id
     * @param $b_channel_id
     * @param int $num
     * @return null
     */
    public function updateChannelidbindingchidsByChannelIdAndBChannelId($channel_id,$b_channel_id,$num=1)
    {
        if(empty($channel_id)||empty($b_channel_id)){
            return false;
        }
        $res=DB::table('channelidbindingchids')
            ->where(array('b_channel_id'=>$b_channel_id,'channel_id'=>$channel_id))
            ->update(array(
                'updated_at'=>time(),
                'state'=>1,
                'num'=>$num,
                'b_channel_id'=>$b_channel_id,
                'channel_id'=>$channel_id,
            ));
        return ($res==1)?true:false;
    }

    /***
     * 优惠券转化二维码
     * @param $channel_id
     * @return array
     */
    public function couponIdExcel2QrImgByChannelId($channel_id){
        if(empty($channel_id)){
            return array('state'=>-2,'message'=>'优惠券不存在');
        }
         $channel=$this->getChannelByChannelId($channel_id);
        if(empty($channel)){
            return array('state'=>-2,'message'=>'优惠券不存在');
        }
        $coupons=DB::table('coupons')
            ->where(array('state'=>1,'channel_id'=>$channel_id))
            ->select('coupon_id','price')
            ->get();
        $qr_img_re=self::coupons2QrImg($coupons,$channel->channel_id);
        if(!empty($qr_img_re)){
            $zip_path=$this->zip->addDirFileListToZip($qr_img_re,'',$channel_id.'.zip');
        }
        if(isset($zip_path)&&!empty($zip_path)){
            $zip_url=asset($zip_path);
            return $zip_url;
        }
        return '';
    }

    /***
     * 优惠券转换成二维码
     * @param $coupons
     * @param $channel_id
     * @return string
     */
    public function coupons2QrImg($coupons,$channel_id){
//        try{
            $qr_url=env('HOME_URL') . 'api/coupons/qrcode?body=';

            $coupon_folder= public_path('coupon' . DIRECTORY_SEPARATOR);
            $data['qr_url']=$qr_url;
            $data['save_path']=$coupon_folder;
            $date_str=date("YmdHis",time());
            $date_simp_str=date("Ym",time());
            $coupon_m_folder=$coupon_folder.$date_simp_str;
            @$this->mkFolder($coupon_m_folder);
            $coupon_channel_folder= $coupon_m_folder.DIRECTORY_SEPARATOR.$channel_id;
            @$this->mkFolder($coupon_channel_folder);
            $coupon_channel_path= $coupon_channel_folder.DIRECTORY_SEPARATOR.$date_str;
            @$this->mkFolder($coupon_channel_path);
            foreach ($coupons as $coupon){
                $coupon_id            = $coupon->coupon_id;
                $price                = $coupon->price;
                $content['coupon_id'] =$coupon_id;
                $content['price']     =$price;
                $content_str          =$data['qr_url'].json_encode($content);
                $arrContextOptions=array(
                    "ssl"=>array(
                        "verify_peer"=>false,
                        "verify_peer_name"=>false,
                    )
                );
                $img = self::get_qrcode_img($content_str);

                file_put_contents($coupon_channel_path.DIRECTORY_SEPARATOR.$coupon_id.'.png',$img);
            }
            return $coupon_channel_path;
//            Log::info($e);
//           return '';
//        }
    }

    static function get_qrcode_img($url){
        $ch         = curl_init ($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, 0);
        $response   = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

    /**
        使用范围id获取渠道编号
     */
    function get_channel_id_by_map_id($input){
        if(!isset($input)) return null;
        $channel_id = $this->couponTool->get_channel_id_by_map_id($input);
        return $channel_id;
    }

    /**
        获取渠道适用分类数据
        参数：
            channel_id          渠道编号
     */
    function get_resource_list_by_channel_id($input){
        $arr = $this->couponTool->get_resource_list_by_channel_id($input);
        $result['product_temp'] = $this->couponTool->getProductTempsByProductTempIds($arr['product_temp']);
        return $result;
    }

    /**
        添加渠道适用范围
        参数：
            type                类型 product_temp产品模版
            channel_id          渠道
            resource_id         资源编号
            price               额度
     */
    function add_channel_map($input){
        if(!isset($input['type']) || !isset($input['channel_id']) || !isset($input['resource_id']))
            return GeneralTool::createResult('','M00002');

        $channel = $this->couponTool->getCouponChannel(['channel_id' => $input['channel_id'],'state' => 1]);
        if(!isset($channel) && !isset($channel->coupon_type)) return GeneralTool::createResult('','M05047');
        $input['type'] = $this->couponTool->get_type_by_input_type($input['type']);
        if($input['type'] == '') return GeneralTool::createResult('','M05049');
        $input['coupon_type'] = $channel->coupon_type;
        $result = $this->couponTool->add_channel_map($input);

        return GeneralTool::createResult('',$result);
    }

    /**
     * 分发优惠券
     * 参数：
     *     user_id              用户编号
     *     coupon_id            优惠券编号
     *     title                标题
     *     message_phone        手机通知栏内容
     *     message              APP消息推送内容
     */
    function send_coupon_to_user($input){
        JpushTool::push($input['message_phone'],
                        0,
                        $input['user_id'].'',
                        ['title'      => $input['title'],
                         'user_id'    => $input['user_id'].'',
                         'class'      => 'system_notification',
                         'type'       => 1,
                         'jump_value' => '',
                         'template_no'=> '2',
                         'message'    => $input['message'],
                         'images'     => [[]]]);
    }

    /**
     * 获取渠道下优惠券列表
     * 参数：
     *     channel_id           渠道编号
     */
    function coupon_list_from_channel($input){
        if(!isset($input['channel_id'])) return GeneralTool::createResult('','M00002');
        $channel = DB::table('channels')->where(['channel_id' => $input['channel_id'],'state' => 1])->first();
        if(!isset($channel)) return ['state' => 'M00001', 'result' => (object)[], 'message' => '渠道不存在'];
        $arr['use'] = DB::table('coupons')
                      ->where(['channel_id' => $input['channel_id'],
                               'state' => 1])
                      ->where('using_time','>',0)
                      ->count();
        $arr['send'] = DB::table('coupons')
                       ->where(['channel_id' => $input['channel_id'],
                               'state' => 1])
                       ->where('user_id','<>','')
                       ->count();
        $arr['data'] = $this->couponTool->coupon_list_from_channel($input);
        return GeneralTool::createResult($arr,'M00000');
    }
}
